package com.turman.blibrary.manager

import android.app.Activity
import android.app.Application
import android.os.Bundle
import java.lang.ref.WeakReference

/**
 * activity管理工具
 * Created by turman on 2022/03/16.
 */
class ActivityManager private constructor() {
    //当前所有打开的activity集合
    private val activityRefs = ArrayList<WeakReference<Activity>>()

    //前后台切换监听
    private val frontbackCallback = ArrayList<FrontBackCallback>()

    private var activityStartCount = 0

    private var front = true

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                activityRefs.add(WeakReference(activity))
            }

            override fun onActivityStarted(activity: Activity) {
                activityStartCount++
                //判断当前app是否为从后台到前台
                if (!front && activityStartCount > 0) {
                    front = true
                    frontbackCallback.forEach {
                        it.onChanged(front)
                    }
                }
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {
                activityStartCount--;
                if (activityStartCount <= 0 && front) {
                    front = false
                    frontbackCallback.forEach {
                        it.onChanged(front)
                    }
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                activityRefs.forEach {
                    if (it != null && it.get() == activity) {
                        activityRefs.remove(it)
                        return@forEach
                    }
                }
            }
        })
    }

    val topActivity: Activity?
        get() {
            if (activityRefs.size <= 0) {
                return null
            } else {
                return activityRefs[activityRefs.size - 1].get()
            }
        }

    fun addFrontbackCallback(callback: FrontBackCallback) {
        frontbackCallback.add(callback)
    }

    fun removeFrontbackCallback(callback: FrontBackCallback) {
        frontbackCallback.remove(callback)
    }

    interface FrontBackCallback {
        fun onChanged(front: Boolean)
    }

    companion object {
        val instance: ActivityManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            ActivityManager()
        }
    }
}